import type { ButtonProps, FormProps, SearchFormProps } from "../types"
import { isObject } from "@/utils"

const defaultSearchBtn: ButtonProps = {
    title: "查询",
    icon: "SearchOutline",
    type: "primary",
    htmlType: "submit"
}

const defaultResetBtn: ButtonProps = { title: "重置", icon: "ClearOutlined" }

/**
 * 查询表单
 */
export function useSearchForm(props: Ref<FormProps>) {
    // 是否收缩
    const collapsedRef = ref<boolean>(true)
    // 收缩展开
    function toggleCollapse() {
        collapsedRef.value = !collapsedRef.value
    }
    // 收缩状态
    const useAdvanceSearch = computed(() => {
        const { search } = unref(props)
        if (search) {
            const searchFormProps = (search === true ? {} : search) as SearchFormProps
            return searchFormProps.useAdvance === true && collapsedRef.value
        } else {
            return false
        }
    })

    // 使用查询按钮
    const searchProps = computed(() => {
        const { search } = unref(props)
        const p: Recordable = { search: false, useAdvance: false }
        if (search === true) {
            p.search = true
            p.searchBtn = { ...defaultSearchBtn }
            p.resetBtn = { ...defaultResetBtn }
        } else if (isObject(search)) {
            p.search = true
            const searchFormProps = search as SearchFormProps
            const { searchBtn, resetBtn, useAdvance } = searchFormProps
            if (isObject(searchBtn)) {
                p.searchBtn = { ...defaultSearchBtn, ...(searchBtn as Partial<ButtonProps>) }
            } else if (searchBtn !== false) {
                p.searchBtn = { ...defaultSearchBtn }
            }
            if (isObject(resetBtn)) {
                p.resetBtn = { ...defaultResetBtn, ...(resetBtn as Partial<ButtonProps>) }
            } else if (resetBtn !== false) {
                p.resetBtn = { ...defaultResetBtn }
            }
            p.useAdvance = useAdvance
        }
        return p
    })

    return { searchProps, useAdvanceSearch, toggleCollapse }
}
